package cn.itcast.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.itcast.UserDao;
import cn.itcast.UserService;
import cn.itcast.pojo.Permission;
import cn.itcast.pojo.Role;
import cn.itcast.pojo.User;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service(interfaceClass =UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
  @Autowired
  UserDao userDao;
    @Override
    public User findByUsername(String username) {
        //根据用户名查询用户id
        User user = userDao.findUserByUsername(username);
        if (user == null) {

            return null;
        }
        Integer userId = user.getId();
        HashMap<String, List<Permission>> map = new HashMap<>();
        //根据用户id查询所有用户角色
        Set<Role> roles = userDao.findUserRoleByUserId(userId);
        if (roles.size() > 0) {
            List<Integer> roleIds = getRoleId(roles);
            //根据用户角色查询用户权限
           Set<Permission> permissions= userDao.findPermission(roleIds);
            System.out.println("permissions = " + permissions);
           //通过角色id分组
            Map<Integer, List<Permission>> permissionMap = permissions.stream().collect(Collectors.groupingBy(Permission::getRoleId));
            for (Role role : roles) {
                HashSet hashSet = new HashSet();
                hashSet.addAll(permissionMap.get(role.getId()));
                role.setPermissions(hashSet);
            }

        }
        user.setRoles(roles);
        return user;
    }
    private List<Integer> getRoleId(Set<Role> roles) {
        ArrayList<Integer> ids = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(roles)){
            for (Role role : roles) {
                ids.add(role.getId());
            }


        }
        return ids;
    }
}
